/*本文件收集封装方法*/


/*
解决苹果浏览器的cookie中不能有';'字符存在
*/
function urlcode(str){
  return encodeURIComponent(str)
}
function urldecode(str){
  return decodeURIComponent(str)
}
/*
**	addCookie 		添加一个cookie
**	params 	
** 	name 	[String]
** 	value 	[String]
** 	iDay 	[Number]
*/
export const addCookie = function (name, value, iDay) {
  if (iDay) {
    //设置过期时间
    var oDate = new Date();
    oDate.setDate(oDate.getDate() + iDay);
    document.cookie = name + '=' + urlcode( value + '; PATH=/; EXPIRES=' + oDate.toGMTString());
  } else {
    //默认不设置过期时间
    if(typeof value == "object"){
      document.cookie = name + '='  + urlcode(JSON.stringify(value) + '; PATH=/');
    }else{
      document.cookie = name + '=' + urlcode(JSON.stringify(value)  + '; PATH=/') ;
    }
    
  }
}

/*
** 	getCookie 		获取一个cookie
** 	params
** 	name 		[String]
*/
export const getCookie = function (name) {
  //name=李四; age=18; sex=男; weight=50
  if(!document.cookie){
    return ""
  }
  var arrs = document.cookie.split('=')
  var cookie =""
  arrs.forEach((item,index) => {
        arrs[index] = urldecode(item)
  });

  cookie = arrs.join("=")
  var arr = cookie.split(';');
  for (var i = 0; i < arr.length; i++) {
    var arr2 = arr[i].split('=');
    if (arr2[0] == name) { 
      return arr2[1];
    }
  }
}
/*
** 	removeCookie 		删除一个cookie
** 	params
** 	name 		[String]
*/
export const removeCookie = function (name) {
  addCookie(name, 1, -1);
}
/**
 * 清除所有cookies
*/
export const clearAllCookie = function () {
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
  if (keys) {
    for (var i = keys.length; i--;)
      document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString() // 清除当前域名下的,例如：m.ratingdog.cn
    document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString() // 清除当前域名下的，例如 .m.ratingdog.cn
    document.cookie = keys[i] + '=0;path=/;domain=ratingdog.cn;expires=' + new Date(0).toUTCString() // 清除一级域名下的或指定的，例如 .ratingdog.cn
  }
}

//localStorage长时间保存，sessionStorage会话结束前
/**
 * 存储localStorage
 */
export const setStorage = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStorage = name => {
  if (!name) return;
  return window.localStorage.getItem(name);
}
/**
 * 移除localStorage
*/
export const removeStorage = (name) => {
  if (!name) return;
  return window.localStorage.removeItem(name);
}
/*
*保存sessionStorage
*/
export const setSession = (name, value) => {
  if (!name) return;
  return window.sessionStorage.setItem(name, value)
}
/**
 * 读取sessionStorage
*/
export const getSession = (name) => {
  if (!name) return;
  return window.sessionStorage.getItem(name)
}
/**
 * 移除session
*/
export const removeSession = (name) => {
  if (!name) return;
  return window.sessionStorage.removeItem(name);
}
/**
 * formDate
*/


/**
 * 将数字取整为10的倍数
 * @param {Number} num 需要取整的值
 * @param {Boolean} ceil 是否向上取整
 * @param {Number} prec 需要用0占位的数量
 * 
// formatInt(2345, 2, true)  -> 2400
// formatInt(2345, 2, false) -> 2300
// formatInt(2345, 3, true)  -> 3000
// formatInt(2345, 3, false) -> 2000
 */
export const formatInt = (num, prec = 2, ceil = true) => {
  const len = String(num).length;
  if (len <= prec) { return num };
  const mult = Math.pow(10, prec);
  return ceil ?
    Math.ceil(num / mult) * mult :
    Math.floor(num / mult) * mult;
}
//判断价格是否有两个小数，没有则补上
export const changeTwoDecimal_f = (x) => {
  var f_x = parseFloat(x)
  if (isNaN(f_x)) {
    return 0
  }
  var f_x = Math.round(x * 100) / 100
  var s_x = f_x.toString()
  var pos_decimal = s_x.indexOf('.')
  if (pos_decimal < 0) {
    pos_decimal = s_x.length
    s_x += '.'
  } while (s_x.length <= pos_decimal + 2) {
    s_x += '0'
  }
  return s_x
}
//压缩图片，
/**
 * @file 传入要压缩的图片
 * @size 大于多少的图片进行压缩，默认2M
 * @imgWidth 压缩后的图片宽度
 * @imgHeight 压缩后的图片高度
 * */
export const compressImages = (file, imgWidth, imgHeight) => {
  // 创建Canvas对象(画布)
  let canvas = document.createElement("canvas");
  // 获取对应的CanvasRenderingContext2D对象(画笔)
  let context = canvas.getContext("2d");
  // 创建新的图片对象
  let img = new Image();
  // 指定图片的DataURL(图片的base64编码数据)
  img.src = file.content;
  // 监听浏览器加载图片完成，然后进行进行绘制
  img.onload = () => {
    // 指定canvas画布大小，该大小为最后生成图片的大小
    canvas.width = imgWidth ? imgWidth : 800;
    canvas.height = imgHeight ? imgHeight : 600;
    /* drawImage画布绘制的方法。(0,0)表示以Canvas画布左上角为起点，400，300是将图片按给定的像素进行缩小。
  如果不指定缩小的像素图片将以图片原始大小进行绘制，图片像素如果大于画布将会从左上角开始按画布大小部分绘制图片，最后的图片就是张局部图。*/

    context.drawImage(img, 0, 0, imgWidth ? imgWidth : 800, imgHeight ? imgHeight : 600);
    // 将绘制完成的图片重新转化为base64编码，file.file.type为图片类型，0.92为默认压缩质量
    file.content = canvas.toDataURL(file.file.type, 0.92);
    // 最后将base64编码的图片保存到数组中，留待上传。

    //把压缩后的base64转换成图片file数据格式，然后用formdata格式上传
    return file.content
  };
}

//base64转成文件file格式
//把压缩后的base64转换成图片file数据格式，然后用formdata格式上传
// let a = this.base64ToFile(file.content)
// let formData = new FormData();
// formData.append('img',a);  
// this.upImg(formData)上传api
export const base64ToFile = function (data, typeName) {
  // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
  let binary = atob(data.split(',')[1]);
  let mime = data.split(',')[0].match(/:(.*?);/)[1];
  let array = [];
  for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  let fileData = new Blob([new Uint8Array(array)], {
    type: mime,
  });
  let file = new File([fileData], `${new Date().getTime()}.${typeName}`, { type: mime });
  return file;
}
/* 使用如下，DOM 倒计时
 <van-button type="default" size="small" @click="setCodeEvent">发送验证码</van-button>
  // 发送验证码
    setCodeEvent(e) {
      countDwon(e.target, 60);
    }
 */
// DOM 倒计时,
/**
 * @el dom元素
 * @count 多少秒
 * @countColor 倒计时颜色
 * @resendColor 重新发送文本颜色
*/
export const countDwon = function (el, count, countColor, resendColor) {
  el.innerHTML = count + "S";
  el.style.pointerEvents = "none";
  el.style.color = countColor ? countColor : '#EE4849';
  let timer = setInterval(() => {
    count--;
    el.innerHTML = count + " S";
    if (count === 0) {
      el.innerHTML = "Resend";
      el.style.pointerEvents = "auto";
      el.style.color = resendColor ? resendColor : '#EE4849';
      clearInterval(timer);
    }
  }, 1000);
}
// 获取url参数 使用getQueryVariable("id") 返回 1
export const getQueryVariable = function (variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}
// 传入对象返回get路径参数
export const getQueryInfo = function (query) {
  let paramStr = ''
  Object.keys(query).forEach(key => {
    paramStr += key + '=' + query[key] + '&'
  })
  if (paramStr) {
    paramStr = paramStr.substring(0, paramStr.length - 1)
  }
  return '?' + paramStr
}
//上传到阿里云oss
export const uploadAli_os=function(name,file){
      let OSS = require('ali-oss');
      let moment = require("moment")
      const client = new OSS({
        // endpoint:'ceshi-share.oss-ap-south-1.aliyuncs.com',
        region: 'oss-ap-south-1',//访问地址
        accessKeyId: 'LTAI4G72DFbUnxnfdertyFaz',//
        secure:true,
        accessKeySecret: 'liQZm1gEyn9UHRS5bcnAv9xOaRCaYL',
        bucket: 'fundimages',
        timeout: 600 * 1000,
        // stsToken: '<security-token>'//可选参数
      });
      var timestamp=moment().format("YYYY-MM-DD")
      const storeAs = `h5/${timestamp}/`+ name;  
      return new Promise((resolve,reject)=>{
        client.multipartUpload(storeAs,file, {}).then(results => {
          resolve(results)
          // if(results.res.requestUrls[0].indexOf('?') != -1){
          //     this.url = results.res.requestUrls[0].split('?')[0];
          // }else{
          //     //console.log('图片100k以内')
          //     this.url = results.res.requestUrls[0]
          // }
      }).catch((err) => {
        console.log(err);
      });
    })
　
}
//金钱转元转分
export const Money = function(value){
           return value*100     
}
